package top.sdrkyj.onecms.controller;

import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Randoms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("api")
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @GetMapping("/captcha")
    public ResponseEntity<byte[]> captcha(HttpSession session) throws IOException {
//        SpecCaptcha captcha = new SpecCaptcha(180, 48, 4);

        // gif类型
        GifCaptcha captcha = new GifCaptcha(180, 48, 4);

        captcha.setFont(new Font("Microsoft YaHei", Randoms.num(4), Randoms.num(25, 45)));  // 有默认字体，可以不用设置
        try {
            captcha.setFont(Randoms.num(10));
        } catch (FontFormatException e) {
            logger.warn("FontFormatException", e);
        }

        session.setAttribute("captcha", captcha.text());

        ByteArrayOutputStream baos = new ByteArrayOutputStream(6 << 10);
        captcha.out(baos);
        return ResponseEntity.status(HttpStatus.OK)
                .header(HttpHeaders.CACHE_CONTROL, CacheControl.noStore().mustRevalidate().getHeaderValue())
                .contentType(MediaType.IMAGE_PNG)
                .body(baos.toByteArray());
    }

}
